package com.example.servicetest

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout
import kotlin.math.min


/**
 * 自定义控件：圆角RelativeLayout
 * 如果想改为圆形view，修改rect_adius为很大的数字，比如100
 */
class PolygonLayout : FrameLayout {

    private val roundRect = RectF()

    private val maskPaint = Paint()

    private val zonePaint = Paint()

    /**
     * 圆角角度
     */
    private var mRoundRadius = 50f

    /**
     * 是否圆形
     */
    private var mIsCircle = true

    private val mPath = Path()

    constructor(context: Context) : this(context,null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs,0)
    constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(
        context,
        attrs,
        defStyle
    ) {
        init()
    }

    private fun init() {
        setLayerType(View.LAYER_TYPE_SOFTWARE,null)
        maskPaint.isAntiAlias = true
        maskPaint.color = Color.RED
        maskPaint.style = Paint.Style.FILL
        maskPaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)

        zonePaint.isAntiAlias = true
        zonePaint.color = Color.BLUE
        zonePaint.style = Paint.Style.FILL

    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        roundRect.set(0f, 0f, width.toFloat(), height.toFloat())
    }

    override fun dispatchDraw(canvas: Canvas) {
        canvasSetLayer(canvas)
        super.dispatchDraw(canvas)
        canvas.restore()
    }

//    override fun draw(canvas: Canvas) {
//        canvasSetLayer(canvas)
//        super.draw(canvas)
//        canvas.restore()
//    }

    /**
     * 重设置圆角
     */
    fun setRoundRadius(radius: Float) {
        if(mIsCircle){
            throw Exception("正圆此参数无效")
        }
        mRoundRadius = radius
        invalidate()
    }


    /**
     * 画布区域裁剪
     */
    private fun canvasSetLayer(canvas: Canvas) {
        if(!mIsCircle){
            canvas.saveLayer(roundRect, zonePaint)
            canvas.drawRoundRect(roundRect, mRoundRadius, mRoundRadius, zonePaint)
            canvas.saveLayer(roundRect, maskPaint)
        }else{
            val radius = min(width,height)
            mPath.addCircle((width/2).toFloat(), (height/2).toFloat(), (radius/2).toFloat(),Path.Direction.CW)
            canvas.saveLayer(roundRect, zonePaint)
//            canvas.drawRect(roundRect,zonePaint)
            canvas.drawPath(mPath,zonePaint)
            canvas.saveLayer(roundRect, maskPaint)
        }
    }
}